﻿using System;
using System.ComponentModel;
using System.Web.UI;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.Core;

namespace Yuanlin.Business
{
    public class ChildArticleCategories : YuanlinUserControl,
        IReplyConverter<NewsCategoryReply, GetListOperation>
    {
        protected Repeater list;
        protected ValuedTextBox searchTextBox;
        protected IButton SearchButton;
        private EntityList newsCategorys;
        private int newsCategoryId = UrlManager.Instance.GetParameterValue<int>(YuanlinParameterName.NewsCategoryId);

        public override void GetRequests(List<BaseRequestBinder> requestBinders)
        {
            if (!IsPostBack)
            {
                NewsCategoryListRequest request = new NewsCategoryListRequest();
                request.UpNewsCategoryId = newsCategoryId;
                request.PageIndex = 0;
                request.PageSize = Int32.MaxValue;
                requestBinders.Add(RequestHelper.BuildGetNewsCategoryListRequest(this, request));
            }
        }
        protected override void OnLoad(EventArgs e)
        {
            if (this.SearchButton != null)
            {
                this.SearchButton.Click += new EventHandler(this.SearchButton_Click);
            }
        }

        private void BindData()
        {
            if (list.DataSource != null)
            {
                return;
            }

            this.list.DataSource = newsCategorys;
            this.list.DataBind();
        }

        private void SearchButton_Click(object sender, System.EventArgs e)
        {
            string path = SiteUrls.Instance().GetArticleListUrl(newsCategoryId);

            if (!string.IsNullOrEmpty(this.searchTextBox.Value))
            {
                if (path.IndexOf("?") > 0)
                {
                    path += string.Format("&QueryText={0}", System.Web.HttpUtility.UrlEncode(this.searchTextBox.Value));
                }
                else
                {
                    path += string.Format("?QueryText={0}", System.Web.HttpUtility.UrlEncode(this.searchTextBox.Value));
                }
            }
            else
            {
                return;
            }

            Page.Response.Redirect(path);
        }

        #region IReplyConverter<NewsCategoryReply,GetListOperation> Members

        public void ConvertReply(NewsCategoryReply reply, GetListOperation operation)
        {
            if (reply != null)
            {
                newsCategorys = reply.EntityList;

                if (!IsPostBack)
                {
                    BindData();
                }
            }
        }

        #endregion
    }
}
